import { Local } from '@/utils/storage';
import YdTable from '@/components/YdTable/index.vue';
import YdForm from '@/components/YdForm/index.vue';
import { downloadFromBlob } from '@/utils/common';
import { ref } from 'vue';

export default {
	name: 'Curd',
	components: {
		YdTable,
		YdForm,
	},
	data() {
		return {
			// 选择的行数据ids
			selectedIds: null,
			// 选择的行数据
			selected: null,
			// 弹出层
			dialog: {
				// 新增或修改
				addOrEdit: {
					// 是否打开
					open: false,
					// 标题
					title: '',
					// 表单数据
					form: {},
					// 表单校验规则
					rule: {},
					// 按钮加载状态
					btnLoading: false,
				},
				// 导入
				imp: {
					// key
					key: -1,
					// ref
					ref: 'uploadRef',
					// 是否打开
					open: false,
					// 标题
					title: '导入',
					headers: {
						Authorization: 'Bearer ' + Local.get('access_token'),
					},
					// 最多导入数
					limit: 1,
					// 下载模板按钮状态
					downloadTemplateBtnLoading: false,
					// 导入确定按钮状态
					importSubmitBtnLoading: false,
				},
				// 新增或修改
				selectUrl: {
					// 是否打开
					open: false,
					// 标题
					title: '',
					// 表单数据
					form: {},
					// 表单校验规则
					rule: {},
					// 按钮加载状态
					btnLoading: false,
				},
			},
		};
	},
	methods: {
		// 表单准备就绪
		handleFormInited() {
			this.handleSearch(null);
		},
		// 搜索
		handleSearch(model: any) {
			this.tableConfig.loading = true;
			console.log(this.formData, 'this.formData');
			this.formData.current = this.formData.pageNum;
			this.formData.size = this.formData.pageSize;
			// this.formData.pageNum = undefined;
			// this.formData.pageSize = undefined;
			this.api
				.query(this.formData)
				.then((res: any) => {
					this.tableConfig.loading = false;
					if (res.code !== 0) {
						this.$message.error(res.msg);
						return;
					}
					if (res.data !== null) {
						this.tableData = res.data.records;
						console.log(this.tableData, 'tableDatatableDatatableData');
						const pagination = this.tableConfig.pagination;
						if (pagination) {
							pagination.total = res.data.total;
						}
					}
				})
				.catch((e: any) => {
					this.tableConfig.loading = false;
				});
		},
		// 表单提交
		handleSubmit(beforeHandleAdd?: () => object, beforeHandleEdit?: () => void) {
			if (this.dialog.addOrEdit.title === '新增') {
				this.handleAdd(beforeHandleAdd);
			} else {
				this.handleEdit(beforeHandleEdit);
			}
		},
		test() {
			console.log(123123);
		},
		// 新增
		handleAdd(beforeHandle?: () => any, isDefaultStatus = false): any {
			// 前置处理
			let defaultForm;
			if (typeof beforeHandle === 'function') {
				defaultForm = beforeHandle() || {};
			}
			// 判断窗口是否打开
			if (!this.dialog.addOrEdit.open) {
				// 表单重置
				this.dialog.addOrEdit.form = defaultForm || {};
				this.dialog.addOrEdit.form.timeout = 300;
				if (isDefaultStatus) {
					this.dialog.addOrEdit.form.status = 1;
				} else {
					this.dialog.addOrEdit.form.status = null;
				}

				// 标题
				this.dialog.addOrEdit.title = '新增';
				// 打开窗口
				this.dialog.addOrEdit.open = true;
				return;
			}

			console.log(this.dialog.addOrEdit.form, 'this.dialog.addOrEdit.form');

			// 校验参数
			this.$refs['addOrEditForm'].validate((valid: any) => {
				if (!valid) {
					return;
				}
				// 调用接口
				this.dialog.addOrEdit.btnLoading = true;
				this.api
					.add(this.dialog.addOrEdit.form)
					.then((res: any) => {
						this.dialog.addOrEdit.btnLoading = false;
						if (res.code !== 0) {
							this.$message.error(res.msg);
							return;
						}
						// 关闭弹出层
						this.dialog.addOrEdit.open = false;
						// 刷新列表
						this.formData.pageNum = 1;
						this.formData.pageSize = this.tableConfig.pagination.pageSize;
						this.tableConfig.pagination.pageNum = 1;
						this.handleSearch(null);
						// 提示
						this.$message.success('新增成功');
					})
					.catch((e: any) => {
						this.dialog.addOrEdit.btnLoading = false;
					});
			});
		},
		// 修改
		handleEdit(beforeHandle?: () => void) {
			// 前置处理
			if (typeof beforeHandle === 'function') {
				beforeHandle();
			}
			// 判断窗口是否打开
			if (!this.dialog.addOrEdit.open) {
				// 数据回显，需要先拷贝一下
				const d = JSON.parse(JSON.stringify(this.selected[0]));
				this.dialog.addOrEdit.form = { ...this.dialog.addOrEdit.form, ...d };
				// 标题
				this.dialog.addOrEdit.title = '修改';
				// 打开窗口
				this.dialog.addOrEdit.open = true;
				return;
			}
			// 校验参数
			this.$refs['addOrEditForm'].validate((valid: any) => {
				if (!valid) {
					return;
				}
				// 调用接口
				this.dialog.addOrEdit.btnLoading = true;
				this.api
					.edit(this.dialog.addOrEdit.form)
					.then((res: any) => {
						this.dialog.addOrEdit.btnLoading = false;
						if (res.code !== 0) {
							this.$message.error(res.msg);
							return;
						}
						// 关闭弹出层
						this.dialog.addOrEdit.open = false;
						// 刷新列表
						this.formData.pageNum = 1;
						this.formData.pageSize = this.tableConfig.pagination.pageSize;
						this.tableConfig.pagination.pageNum = 1;
						this.handleSearch(null);
						// 提示
						this.$message.success('修改成功');
					})
					.catch((e: any) => {
						this.dialog.addOrEdit.btnLoading = false;
					});
			});
		},
		// 删除
		handleDelete(beforeHandle?: () => void) {
			this.$confirm('是否确认删除所选项？', '警告', {
				confirmButtonText: '确定',
				cancelButtonText: '取消',
				type: 'warning',
			})
				.then(() => {
					// 前置处理
					if (typeof beforeHandle === 'function') {
						beforeHandle();
					}
					// 调用接口
					return this.api.remove(this.selectedIds);
				})
				.then(() => {
					// 刷新列表
					this.formData.pageNum = 1;
					this.formData.pageSize = this.tableConfig.pagination.pageSize;
					this.tableConfig.pagination.pageNum = 1;
					this.handleSearch(null);
					// 提示
					this.$message.success('删除成功');
				});
		},
		// 选择行数据
		handleSelectionChange(selects: any) {
			this.selectedIds = selects.map((item: any) => item.id);
			this.selected = selects;
		},
		// 上传前
		handleBeforeUpload(file: object) {
			const fileSuffix = file.name.substring(file.name.lastIndexOf('.') + 1);
			const whiteList = ['xls', 'xlsx'];
			if (whiteList.indexOf(fileSuffix) === -1) {
				this.$message.error('上传文件只能是 xls、xlsx 格式');
				return false;
			}
		},
		// 导入
		handleImport() {
			if (!this.dialog.imp.open) {
				this.dialog.imp.open = true;
				return;
			}
			this.$refs[this.dialog.imp.ref].submit();
		},
		// 上传超过最大数量限制时
		handleUploadOnExceed() {
			this.$message.warning('最多上传' + this.dialog.imp.limit + '个文件');
		},
		// 导入时
		handleUploadOnProgress() {
			this.dialog.imp.importSubmitBtnLoading = true;
		},
		// 导入成功
		handleUploadOnSuccess(res: object) {
			this.dialog.imp.importSubmitBtnLoading = false;
			if (res.code !== 0) {
				this.$message.warning(res.msg);
				return;
			}
			this.dialog.imp.open = false;
			this.handleSearch(null);
			this.$message.success(res.msg);
		},
		// 导入失败
		handleUploadOnError() {
			this.dialog.imp.importSubmitBtnLoading = false;
			this.dialog.imp.open = false;
			this.$message.error('导入失败');
		},
		// 下载导入模板
		downloadTemplate(fileName: string) {
			this.dialog.imp.downloadTemplateBtnLoading = true;
			this.api
				.downloadTemplate()
				.then((res: object) => {
					downloadFromBlob(res, fileName).then((o: object) => {
						this.dialog.imp.downloadTemplateBtnLoading = false;
						if (!o.flag) {
							this.$message.warning(o.msg);
						}
					});
				})
				.catch((e: any) => {
					this.dialog.imp.downloadTemplateBtnLoading = false;
				});
		},
	},
};
